package data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import domain.Busqueda;
import domain.Manifestacion;

public class JDBCBusquedaDAO implements IBusquedaDAO {
	
	@Override
	public Busqueda crearBusqueda(String key, Integer userId, String tematica, String ciudad) {
		Busqueda b = null;
		PreparedStatement stmt = null;
		try{
			String idsM = "";
			List<Manifestacion> manis = null;
			if(tematica.equals("") && ciudad.equals("") && !key.equals(""))
				manis = JDBCManifestacionDAO.buscaManifestaciones(key, key);
			else if(!tematica.equals(""))
				manis = JDBCManifestacionDAO.buscaManifestaciones(tematica, "");
			else if(!ciudad.equals(""))
				manis = JDBCManifestacionDAO.buscaManifestaciones("", ciudad);
			else if(key.equals(""))
				manis = JDBCManifestacionDAO.buscaManifestaciones("", "");
			else
				manis = JDBCManifestacionDAO.buscaManifestaciones("", "");
			 
			for(int i = 0; i < manis.size(); i++){
				if(i == manis.size() - 1)
					idsM += manis.get(i).getManifestacionOID();
				else
					idsM += manis.get(i).getManifestacionOID() + ",";
			}
			Connection conn = ConnectionManager.getInstance().checkOut();
			b = new Busqueda(key, userId);
			b.setSearched(manis);
			String sql = "";
			
			String sql2 = "SELECT * FROM busqueda WHERE userId = ?;";
			stmt = conn.prepareStatement(sql2);
			stmt.setInt(1, userId);
			ResultSet result = stmt.executeQuery();
			if(result.next()){
				sql = "UPDATE busqueda SET key = ?, searched = ?, currentView = ? WHERE userId = ?;";
				stmt=conn.prepareStatement(sql);
				stmt.setInt(4, userId);
				stmt.setString(3, String.valueOf(b.getCurrentView().getManifestacionOID()));
	        	stmt.setString(2, idsM);
	            stmt.setString(1, key);
	            stmt.executeUpdate();
			} else {
				sql = "INSERT INTO busqueda (userId, key, searched, currentView) VALUES (?, ?, ?, ?);";
				stmt=conn.prepareStatement(sql);
				stmt.setString(4, String.valueOf(b.getCurrentView().getManifestacionOID()));
	        	stmt.setString(3, idsM);
	            stmt.setString(2, key);
	            stmt.setInt(1, userId);
	            stmt.executeUpdate();
			}
			
            ConnectionManager.getInstance().checkIn(conn);
            
		} catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
        }
		return b;
	}

	@Override
	public Busqueda selecccionarBuscado(Integer userId,	String currentSearched) {
		Busqueda b = null;
		PreparedStatement stmt = null;
		try{
			Connection conn = ConnectionManager.getInstance().checkOut();
			String sql = "";
			String sql2 = "SELECT * FROM busqueda WHERE userId = ?;";
			stmt = conn.prepareStatement(sql2);
			stmt.setInt(1, userId);
			ResultSet result = stmt.executeQuery();
			if(result.next()){
				sql = "UPDATE busqueda SET currentView = ? WHERE userId = ?;";
				stmt=conn.prepareStatement(sql);
				stmt.setInt(2, userId);
				stmt.setString(1, currentSearched);
				stmt.executeUpdate();
				b = new Busqueda("", userId);
				b.setCurrentView(JDBCManifestacionDAO.getManifestacion2(Integer.parseInt(currentSearched)));
			} else {
				b = this.crearBusqueda("", userId, "", "");
			}
			ConnectionManager.getInstance().checkIn(conn);
		} catch (SQLException e) {
            System.out.println("Message: " + e.getMessage());
            System.out.println("SQLState: " + e.getSQLState());
            System.out.println("ErrorCode: " + e.getErrorCode());
        } finally {
            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
            }
        }
		return b;
	}

}
